/*******************************************************************************

"FreePastry" Peer-to-Peer Application Development Substrate

Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute 
for Software Systems.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

- Neither the name of Rice  University (RICE), Max Planck Institute for Software 
Systems (MPI-SWS) nor the names of its contributors may be used to endorse or 
promote products derived from this software without specific prior written 
permission.

This software is provided by RICE, MPI-SWS and the contributors on an "as is" 
basis, without any representations or warranties of any kind, express or implied 
including, but not limited to, representations or warranties of 
non-infringement, merchantability or fitness for a particular purpose. In no 
event shall RICE, MPI-SWS or contributors be liable for any direct, indirect, 
incidental, special, exemplary, or consequential damages (including, but not 
limited to, procurement of substitute goods or services; loss of use, data, or 
profits; or business interruption) however caused and on any theory of 
liability, whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even if 
advised of the possibility of such damage.

*******************************************************************************/ 
/*
 * Created on Jun 24, 2005
 */
package rice.tutorial.past;

import java.io.IOException;
import java.net.*;
import java.util.Vector;

import rice.Continuation;
import rice.environment.Environment;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.Application;
import rice.p2p.commonapi.RouteMessage;
import rice.p2p.commonapi.Message;
import rice.p2p.commonapi.Endpoint;
import rice.p2p.past.*;
import rice.pastry.*;
import rice.pastry.commonapi.PastryIdFactory;
import rice.pastry.socket.SocketPastryNodeFactory;
import rice.pastry.standard.RandomNodeIdFactory;
import rice.persistence.*;
import rice.tutorial.lesson3.MyMsg;

/**
 * This tutorial shows how to use Past.
 * 
 * @author Jeff Hoye, Jim Stewart, Ansley Post
 */
public class PastAdmin implements Application {
  /**
   * this will keep track of our Past applications
   */
      Past app;
      NodeIdFactory nidFactory;
      PastryNodeFactory factory;
      PastryIdFactory localFactory;
      PastryIdFactory idf;
      PastryNode node;
      Environment env;
      String statusBar;
  protected Endpoint endpoint;
  /**
   * Based on the rice.tutorial.scribe.ScribeTutorial
   * 
   * This constructor launches numNodes PastryNodes. They will bootstrap to an
   * existing ring if one exists at the specified location, otherwise it will
   * start a new ring.
   * 
   * @param bindport the local port to bind to
   * @param bootaddress the IP:port of the node to boot from
   * @param numNodes the number of nodes to create in this JVM
   * @param env the Environment
   */
    @SuppressWarnings("LeakingThisInConstructor")
  public PastAdmin(int bindport, InetSocketAddress bootaddress, final Environment env) throws Exception {
    
    // Generate the NodeIds Randomly
    this.nidFactory = new RandomNodeIdFactory(env);
    this.env = env;


    // construct the PastryNodeFactory, this is how we use rice.pastry.socket
    this.factory = new SocketPastryNodeFactory(this.nidFactory, bindport, env);

    // construct a node, passing the null boothandle on the first loop will
    // cause the node to start its own ring
    this.node = this.factory.newNode();

      
    this.endpoint = this.node.buildEndpoint(this, "myinstance");
    this.endpoint.register();
      
    // used for generating PastContent object Ids.
    // this implements the "hash function" for our DHT
    this.idf = new rice.pastry.commonapi.PastryIdFactory(env);

    // create a different storage root for each node
    String storageDirectory = "/tmp/storage/"+ node.getId().hashCode();

    // create the persistent part
    // Storage stor = new PersistentStorage(idf, storageDirectory, 4 * 1024 * 1024, node
    // .getEnvironment());
    Storage stor = new PersistentStorage(this.idf, storageDirectory, 512 * 1024 * 1024, node.getEnvironment());

    this.app = new PastImpl(node, new StorageManagerImpl(this.idf, stor, new LRUCache(
      new MemoryStorage(this.idf), 512 * 1024, node.getEnvironment())), 0, "");

    node.boot(bootaddress);

    // the node may require sending several messages to fully boot into the ring
    synchronized(node) {

      while(!node.isReady() && !node.joinFailed()) {

        // delay so we don't busy-wait
        node.wait(500);

        // abort if can't join
        if (node.joinFailed()) {

          throw new IOException("Could not join the FreePastry ring.  Reason:" +
                                node.joinFailedReason()); 
        }
      }       
    }

    System.out.println("Finished creating new node " + node);      
    
    // We could cache the idf from whichever app we use, but it doesn't matter
    this.localFactory = new rice.pastry.commonapi.PastryIdFactory(env);
  
  }
  
  public boolean EnviaArquivo(byte[] data, String key) throws InterruptedException, Exception {
    
    int count = 0;
      
    // build the past content
    final PastContent myContent = new Block(this.idf.buildId(key), data);
    // store the key for a lookup at a later point
    final Id storedKey = myContent.getId();
      
    // pick a random past appl on a random node
      
    System.out.println("Inserting " + key);
      
    final Complete done = new Complete(0);
        
    // insert the data
    final String k = key;
    final Past p = this.app;
    final LockManager l = new LockManagerImpl(this.env);
    do {
        l.lock(storedKey, new Continuation() {

            @Override
            public void receiveResult(Object r) {

                p.insert(myContent, new Continuation() {

                  public void receiveResult(Object result) {

                    System.out.println(k + " was successfully stored.");
                    done.setStatus(1);
                    l.unlock(storedKey);

                  }

                  public void receiveException(Exception result) {

                     System.out.println("Error storing " + myContent);
                     done.setStatus(-1);
                     l.unlock(storedKey);

                  }
                });
            }

            @Override
            public void receiveException(Exception e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });
        int t = 0;
        while(done.getStatus() == 0)
        {
            if(t++ > 64) {
                throw new Exception("Erro lookup continuation");
            }
            Thread.sleep(100);
        }

        if(done.getStatus() > 0) {
            return true;
        }
        count++;
        System.out.println("CONTADORRR!!! " + count);

        if(count > 15) {

            return false;
        }

        done.setStatus(0);
    }
    while (true);
    
 }
 
  public byte[] BuscaArquivo(String key) throws InterruptedException, Exception {
    
    int count = 0;
      
    final Id lookupKey = this.localFactory.buildId(key);
    final Complete done = new Complete(0);
    
    // insert the data
    final String k = key;
    final Past p = this.app;
    final LockManager l = new LockManagerImpl(this.env);
    
    do {
        l.lock(lookupKey, new Continuation() {

            @Override
            public void receiveResult(Object r) {

                p.lookup(lookupKey, new Continuation() {

                       // the result is an Array of Booleans for each insert

                  public void receiveResult(Object result) {

                    System.out.println(k + " was successfully retrived.");
                    done.setStatus(1);
                    Block r = (Block) result;
                    done.setData(r.getContent());
                    l.unlock(lookupKey);

                  }

                  public void receiveException(Exception result) {

                     System.out.println("Error retrieving" + k);
                     done.setStatus(-1);
                     l.unlock(lookupKey);

                  }
                });
            }

            @Override
            public void receiveException(Exception e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });
        int t = 0;
        while(done.getStatus() == 0)
        {
            if(t++ > 64) {
                throw new Exception("Erro lookup continuation");
            }
            Thread.sleep(100);
        }
        
        if(done.getStatus() > 0) {
            
            return done.getData();
        }
        count++;
        System.out.println("CONTADORRR!!! " + count);

        if(count > 15) {

            throw new Exception("Error retrieving file.");
        }
        
        done.setStatus(0);
    }
    while (true);
  }    
  
    
  /**
   * Called to directly send a message to the nh
   */
  public boolean EnviaEntradaCatalogo(NodeHandle nh, String content) {
    
    System.out.println(this + " enviando " + content + " para " + nh);    
    
    //Message msg = new MyMsg(endpoint.getId(), nh.getId(), content);
    //endpoint.route(null, msg, nh);
    
    System.out.println(this.node.getId().distanceFromId(this.localFactory.buildId("catalogo")));


    return true;
  }
  
  public void BuscaCatalogo(NodeHandle nh) {
    
    System.out.println(this + " enviando requisição ao catalogo " + nh);    
    
    //Message msg = new MyMsg(endpoint.getId(), nh.getId());
    //endpoint.route(null, msg, nh);

  }
      
  public String toString() {
    
    return "MyApp " + endpoint.getId();
  }

  
  public void deliver(Id id, Message msg) {
  
      
  }
  
  /**
   * Usage: java [-cp FreePastry- <version>.jar]
   * rice.tutorial.past.PastAdmin localbindport bootIP bootPort numNodes
   * example java rice.tutorial.past.PastAdmin 9001 pokey.cs.almamater.edu 9001 10
   */
  public static void main(String[] args) throws Exception {
    
//    args[1] = "9001";
//    args[2] = "10.66.148.40";
//    args[3] = "9001";
//    args[4] = "5";
    
    // Loads pastry configurations
    Environment env = new Environment();

    // disable the UPnP setting (in case you are testing this on a NATted LAN)
    env.getParameters().setString("nat_search_policy","never");
    
    try {
      
      // the port to use locally
      int bindport = Integer.parseInt(args[0]);
      // build the bootaddress from the command line args
      InetAddress bootaddr = InetAddress.getLocalHost();
      int bootport = Integer.parseInt(args[1]);
      InetSocketAddress bootaddress = new InetSocketAddress(bootaddr, bootport);

      
      // launch our node!
      PastAdmin dt = new PastAdmin(bindport, bootaddress, env);
      byte[] data = "teste".getBytes();
      final PastContent myContent = new Block(dt.idf.buildId("teste"), data);
    
    } catch (Exception e) {
      
      // remind user how to use
      System.out.println("Usage:");
      
      System.out
          .println("java [-cp FreePastry-<version>.jar] rice.tutorial.past.PastTutorial localbindport bootIP bootPort numNodes");
      
      System.out
          .println("example java rice.tutorial.past.PastTutorial 9001 pokey.cs.almamater.edu 9001 10");
      
      throw e;
    }
  }

    @Override
    public boolean forward(RouteMessage rm) {
//        throw new UnsupportedOperationException("Not supported yet.");
          return true;
    }

    @Override
    public void update(NodeHandle nh, boolean bln) {
//        throw new UnsupportedOperationException("Not supported yet.");
    }

    
}
